/**
 * Created by zhoulin on 2019/4/3.
 */
var deptId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.deptId);
var isChildren = 1; // todo 1：包含子部门，2：不包含子部门
var sexMap = new Map();
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);

//表格初始化配置
var tableInit = function () {

    var columns = [
        {
            title: '全选',
            field: 'select',
            //复选框
            checkbox: true,
            width: 25,
            align: 'center',
            valign: 'middle'
        }, {
            field: 'id',
            title: 'ID',
            align: 'center',
            width: 30,
            sortable: true,
            visible: false
        }, {
            field: 'headerImgUrl',
            title: '头像',
            align: 'center',
            formatter: function (value) {
                if (!empty(value)) {
                    var img_html = "<a href='" + value + "' title='点击查看大图' target='_blank'>" +
                        "<img src='" + value + "' width='40' onerror='imgNotfind(event);' /></a>";
                    return img_html;
                } else {
                    return "<img src='" + value + "' width='40' onerror='imgNotfind(event);' />";
                }
            }
        }, {
            field: 'name',
            title: '名称',
            align: 'center',
            sortable: false
        }, {
            field: 'sex',
            title: '性别',
            align: 'center',
            sortable: false,
            formatter: function (value) {
                return sexMap.get(value.toString());
            }
        }, {
            field: 'deptName',
            title: '部门',
            align: 'center',
            sortable: false
        }, {
            field: 'stationName',
            title: '职位',
            align: 'center',
            sortable: false
        }, {
            field: 'wxTel',
            title: '微信关联电话',
            align: 'center',
            visible: true
        }, {
            field: 'phone',
            title: '常用电话',
            align: 'center',
            visible: false
        }, {
            field: 'wxCode',
            title: '微信号',
            align: 'center',
            visible: false,
        }, {
            field: 'wxImgUrl',
            title: '微信二维码',
            align: 'center',
            formatter: function (value) {
                if (!empty(value)) {
                    var img_html = "<a href='" + value + "' title='点击查看大图' target='_blank'>" +
                        "<img src='" + value + "' width='40' onerror='imgNotfind(event);' /></a>";
                    return img_html;
                } else {
                    return "<img src='" + value + "' width='40' onerror='imgNotfind(event);' />";
                }
            }
        }, {
            field: 'isShow',
            title: '前端展示',
            align: 'center',
            formatter: function (value, lin) {
                return `<input type='checkbox' datd-id=${lin.id} ${value ? value == 1 ? 'checked' : '' : ''} class='show_status_switch'`;
            }
        }, {
            field: 'gmtCreate',
            title: '创建时间',
            align: 'center',
            sortable: false,
            visible: false,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        }, {
            field: 'gmtModified',
            title: '修改时间',
            align: 'center',
            sortable: false,
            visible: false,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        },
    ];

    //请求服务数据时所传参数
    function queryParams(params) {
        return {
            pageNumber: params.pageNumber,
            pageSize: params.pageSize,
            searchText: params.searchText,
            sortName: params.sortName,      //排序列名
            sortOrder: params.sortOrder, //排位命令（desc，asc）
            isChildren: isChildren,
            deptId: deptId
        }
    }

    function initSwitch() {
        $('.show_status_switch').bootstrapSwitch({
            onText: "启用",      // 设置ON文本  
            offText: "禁用",    // 设置OFF文本  
            onColor: "success",// 设置ON文本颜色(info/success/warning/danger/primary)  
            offColor: "danger",  // 设置OFF文本颜色 (info/success/warning/danger/primary)  
            size: "small",    // 设置控件大小,从小到大  (mini/small/normal/large)  
            // 当开关状态改变时触发  
            onSwitchChange: function (event, state) {
                let id = event.target.attributes['datd-id'].nodeValue;
                console.log(id)
                console.log(state)
                if (state)
                    layer.msg('已开启', { time: 1500, icon: 6 });
                else
                    layer.msg('已禁用', { time: 1500, icon: 5 });
            }
        })
    }

    var tableConfig = $.extend(bootstrapTableConfig(_HOST + _API.business_manage_staff_list, queryParams, columns), {
        //这里是其他的一些个性化的 bootstrap-table options
        //例如 覆盖一些公共的配置
        //例如 添加一些私有的配置
        showColumns: true,//列显示操作按钮
        ajaxOptions: { //设置自定义请求头
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': 'staff:list'
            }
        },
        //例如格式化数据
        responseHandler: function (res) {
            //在ajax获取到数据，渲染表格之前，修改数据源
            //console.log(res)
            if (res.success) {
                //更新本地token
                sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.token, res.token);
            }
            return res;
        },
        //加载成功
        onLoadSuccess: function () {
            initSwitch();
        }
    });
    //调用实例化
    $('#bootstrapTableEvents').bootstrapTable(tableConfig);
    $(".search input").attr('placeholder', '姓名/部门/职位/手机号/微信号');
};

var app = new Vue({
    el: '#app',
    data: {
        permissions: ['staff:add', 'staff:update', 'staff:del', 'department:list', 'appRole:modifyUserRole', 'staff:certificate'],
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", { time: 1500, icon: 5 });
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200)

            return;
        }
        that.getDictionary()
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        //获取字典表配置数据
        getDictionary: function () {
            var that = this;
            var params = "?keyTable=sex"
            Get(that, _HOST + _API.common_dic_dicList + params)
                .then(function (response) {
                    // 响应成功回调
                    //console.log(response)
                    if (response) {
                        if (response.success) {
                            var list = response.list
                            for (var item in list) {
                                sexMap.set(list[item].keyS.toString(), list[item].keyValue.toString())
                            }
                        } else {
                            layer.msg(response.msg, { time: 1500, icon: 5 });
                        }
                    }
                    //初始化设置zTree
                    that.initTree();
                })
        },
        // 配置证书
        addCertificate: function () {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length != 1) {
                layer.msg('请选中一条数据', { time: 1500, icon: 5 });
                return;
            }
            var loadingIndex = layer.load(2, { //icon支持传入0-2
                shade: [0.5, 'gray'], //0.5透明度的灰色背景
                content: '数据加载中...',
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '39px',
                        'width': '60px'
                    });
                }
            });
            var setting = {
                check: {
                    enable: true,
                    chkStyle: "radio",
                    radioType: "all"   //对所有节点设置单选
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "parentId",
                        rootPId: 0
                    }
                },
                callback: {
                    onClick: function (e, treeId, treeNode, clickFlag) {
                        zTreee.checkNode(treeNode, !treeNode.checked, true);
                    }
                },
            }, zTreee;
            var zNodes = [];
            Get(that, _HOST + _API.user_certificate_certificateList + "?pageNo=" + 1 + "&pageSize=" + 1000 + "&companyId=" + companyId + "&loginId=" + list[0].loginId)
                .then(function (response) {
                    // 响应成功回调
                    //console.log(response)
                    if (response) {
                        if (response.success) {
                            var html = '<ul id="treeDemo2" class="ztree"></ul>';
                            var confirm = layer.confirm(html, {
                                title: "添加证书",
                                btn: ['确定', '取消'], //按钮
                                shadeClose: false,
                                area: ['40%', '98%']
                            }, function () {
                                //选中部门
                                var zTree = $.fn.zTree.getZTreeObj("treeDemo2");
                                nodes = zTree.getCheckedNodes(true);
                                var ids = [];
                                for (let i = 0; i < nodes.length; i++) {
                                    ids.push(nodes[i].id);
                                }
                                // 保存
                                that.updateRelation(ids.join(','), list[0].loginId);
                                layer.close(confirm);
                            });

                            zTreee = $.fn.zTree.init($("#treeDemo2"), setting, response.list);
                            var treeObj = $.fn.zTree.getZTreeObj("treeDemo2");

                            var nodes = treeObj.getNodes();
                            if (nodes.length > 0) {
                                for (var i = 0; i < nodes.length; i++) {
                                    treeObj.expandNode(nodes[i], true, false, false);//默认展开第一级节点
                                }
                            }
                            layer.close(loadingIndex);
                        } else {
                            layer.msg(response.msg, { time: 1500, icon: 5 });
                        }
                    }
                })
        },
        updateRelation: function (ids, loginId) {
            var that = this;
            var param = {};
            param.ids = ids;
            param.loginId = loginId;
            param.companyId = companyId;
            Post(that, _HOST + _API.user_certificate_updateRelation, param, false)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            $('#bootstrapTableEvents').bootstrapTable('refresh');
                            layer.msg(response.msg, { time: 1500, icon: 1 });
                        } else {
                            layer.msg(response.msg, { time: 1500, icon: 5 });
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        //添加
        add: function () {
            var that = this;
            var index = layer.open({
                type: 2,
                title: "新增",
                content: "edit.html?id=",
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
            layer.full(index);
        },
        //修改
        update: function () {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', { time: 1500, icon: 5 });
                return;
            }
            list = list[0];
            var index = layer.open({
                type: 2,
                title: "修改",
                content: "edit.html?id=" + list.id,
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
            layer.full(index);
        },
        //删除
        del: function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', { time: 1500, icon: 5 });
                return;
            }

            var ids = "";
            for (var item in list) {
                ids += list[item].id + ",";
            }
            var confirm = layer.confirm('确定删除选项？', {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Put(that, _HOST + _API.business_manage_staff_delete + ids, {}, true, that.permissions[index])
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response)
                        layer.close(confirm);
                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                        if (response) {
                            if (response.success) {
                                layer.msg(response.msg, { time: 1500, icon: 1 });
                            } else {
                                layer.msg(response.msg, { time: 2000, icon: 5 });
                            }
                        }
                    })
            });

        },
        //是否包含子部门员工点击事件
        isChildrenf: function () {
            if (1 == isChildren) {
                isChildren = 2;
            } else {
                isChildren = 1;
            }
            $('#bootstrapTableEvents').bootstrapTable('refresh');
        },
        //分配角色
        assignRoles: function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', { time: 1500, icon: 5 });
                return;
            }
            //获取当前登录人拥有的角色
            Get(that, _HOST + _API.business_appRole_getAllRole)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response)
                    if (response) {
                        if (response.success) {
                            console.log(response.list)
                            var html = "<div id='roses'>";
                            for (var item in response.list) {
                                html = html + '<label class="checkbox-inline i-checks"><input type="checkbox" name="roleId" value="' + response.list[item].id + '"> ' + response.list[item].name + '</label>'
                            }
                            html += "</div>"

                            var confirm = layer.confirm(html, {
                                title: "角色",
                                btn: ['分配角色', '取消'], //按钮
                                shadeClose: false,
                                area: ['50%', '50%']
                            }, function () {
                                console.log("确定")
                                //选中角色
                                var aRoleList = [];
                                var roleId = [];
                                $("#roses input[name='roleId']:checked").each(function () {
                                    aRoleList.push({ "sid": list[0].id, 'rid': $(this).val() })
                                    roleId.push({ 'rid': $(this).val() })
                                })

                                if (roleId.length <= 0) {
                                    layer.msg('请选择角色', { time: 1500, icon: 5 });
                                    return;
                                }

                                console.log(aRoleList)

                                Put(that, _HOST + _API.business_appRole_modifyUserRole, aRoleList, true, that.permissions[index])
                                    .then(function (response) {
                                        // 响应成功回调
                                        console.log(response)
                                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                                        if (response) {
                                            if (response.success) {
                                                layer.msg(response.msg, { icon: 1 });
                                            } else {
                                                layer.msg(response.msg, { time: 1500, icon: 5 });
                                            }
                                        }
                                    })

                            });
                            $(".i-checks").iCheck({ checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green", });

                            Get(that, _HOST + _API.business_appRole_getUserRole + "/" + list[0].id)
                                .then(function (response) {
                                    console.log(response.list)
                                    for (var item in response.list) {
                                        $("#roses input[name='roleId'][value='" + response.list[item].rid + "']").iCheck('check');
                                    }
                                })

                        } else {
                            layer.msg(response.msg, { time: 1500, icon: 5 });
                        }
                    }
                })

        },
        //初始化部门树
        initTree: function () {
            var that = this;
            var loadingIndex = layer.load(2, { //icon支持传入0-2
                shade: [0.5, 'gray'], //0.5透明度的灰色背景
                content: '数据加载中...',
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '39px',
                        'width': '60px'
                    });
                }
            });
            var setting = {
                check: {
                    enable: false,
                    chkStyle: "radio",
                    radioType: "all"   //对所有节点设置单选
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "parentId",
                        rootPId: 0
                    }
                },
                callback: {
                    onClick: function (e, treeId, treeNode, clickFlag) {
                        console.log(treeNode)
                        deptId = treeNode.id;
                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                        zTreee.checkNode(treeNode, !treeNode.checked, true);
                    }
                },
            }, zTreee;
            var zNodes = [];
            Get(that, _HOST + _API.business_manage_sysDepartment_list + "/" + deptId, that.permissions[3])
                .then(function (response) {
                    // 响应成功回调
                    //console.log(response)
                    if (response) {
                        if (response.success) {
                            zNodes = response.list;
                            deptId = zNodes[0].id;
                            //初始化表格
                            tableInit();

                            zTreee = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                            var treeObj = $.fn.zTree.getZTreeObj("treeDemo");

                            var nodes = treeObj.getNodes();
                            if (nodes.length > 0) {
                                for (var i = 0; i < nodes.length; i++) {
                                    treeObj.expandNode(nodes[i], true, false, false);//默认展开第一级节点
                                }
                            }
                            layer.close(loadingIndex);
                        } else {
                            layer.msg(response.msg, { time: 1500, icon: 5 });
                        }
                    }
                })
        }
    },
})

/**
 * 是否包含子部门员工点击事件
 */
$("#isChildren input:checkbox[name='isChildren']").on('ifChecked', function (event) {
    app.isChildrenf();
});
$("#isChildren input:checkbox[name='isChildren']").on('ifUnchecked', function (event) {
    app.isChildrenf();
});